package com.cai.baselibrary.mvp.view

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.launcher.ARouter
import com.cai.baselibrary.model.EventBean
import com.cai.baselibrary.mvp.IView
import com.cai.baselibrary.mvp.presenter.IPresenter
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**基类Activity*/
abstract class BaseActivity: AppCompatActivity(), IView {

    /**建立集合是防止出现多个以后的处理方式会发生改变*/
    private val mAllPresenters = HashSet<IPresenter<*>>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(getContentView())

        //全局路由注解
        ARouter.getInstance().inject(this)

        addPresenters()
        mAllPresenters.forEach { it.onCreate(intent) }
    }



    override fun onStart() {
        super.onStart()
        if (isRegisteredEventBus()){
            EventBus.getDefault().register(this)
        }

        mAllPresenters.forEach { it.onStart() }
    }

    override fun onResume() {
        super.onResume()
        mAllPresenters.forEach { it.onResume() }
    }

    override fun onPause() {
        super.onPause()
        mAllPresenters.forEach { it.onPause() }
    }

    override fun onStop() {
        super.onStop()

        if (isRegisteredEventBus()) {
            EventBus.getDefault().unregister(this)
        }
        mAllPresenters.forEach { it.onStop() }
    }

    override fun onDestroy() {
        super.onDestroy()
        mAllPresenters.forEach { it.onDestroy() }
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
     fun <T> onMessageEvent(event: EventBean<T>) { /* Do something */
        onEventBus(event)
    }


    //--------------------------------------------------------

    protected open fun <T> onEventBus(data: EventBean<T>){

    }

    /**
     * 是否注册EventBus
     * return true返回注册监听。false取消注册
     */
    protected open fun isRegisteredEventBus():Boolean{

        return false
    }


    //-------------------------------------------------------

    /**返回布局*/
    protected abstract fun getContentView():Int @SuppressLint("SupportAnnotationUsage") @LayoutRes



    open fun getPresenters():MutableList<IPresenter<*>>{
        return mutableListOf(mPresenter)
    }

    private fun addPresenters() {
        getPresenters().forEach { mAllPresenters.add(it)}
    }





}


